package com.ruoyi.framework.service;

import com.eic.common.util.ExceptionUtils;
import com.eic.framework.core.security.SecurityLoginService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.model.AdminLoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.UserPasswordRetryLimitService;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dao.SysUser;
import com.ruoyi.system.domain.persist.SysUserPo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private UserPasswordRetryLimitService loginErrorOverService;

    @Autowired
    private SecurityLoginService securityLoginService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        try {
            SysUser user = userService.selectUserByUserName(username);
            if (StringUtils.isNull(user)) {
                logger.info("登录用户：{} 不存在.", username);
                throw new ServiceException("登录用户：" + username + " 不存在");
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                logger.info("登录用户：{} 已被删除.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                logger.info("登录用户：{} 已被停用.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已停用");
            }
            if(loginErrorOverService.isOverload(user.getUserId())){
                throw new ServiceException(MessageUtils.message("user.password.retry.limit.exceed", RuoYiConfig.getMaxRetryCount(), RuoYiConfig.getLockTime()));
            }
            if(userService.matchPasswd(user.getUserId(),password)){
                AdminLoginUser loginUser=new AdminLoginUser();
                loginUser.setUserId(user.getUserId());
                loginUser.setDeptId(user.getDeptId());
                loginUser.setUserName(username);
                SecurityUtils.setLoginUser(loginUser);
                userService.updateLoginIp(user.getUserId());
                securityLoginService.recordLoginInfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
                loginErrorOverService.success(user.getUserId());
                return loginUser.getToken();
            }else{
                throw new ServiceException(MessageUtils.message("user.password.retry.limit.count", loginErrorOverService.error(user.getUserId())));
            }
        } catch (Exception e) {
            securityLoginService.recordLoginInfor(username, Constants.LOGIN_FAIL, e.getMessage());
            throw ExceptionUtils.runTimeException(e);
        }
    }

    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();

        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }
        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            SysUserPo sysUser = new SysUserPo();
            sysUser.setUserName(username);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                securityLoginService.recordLoginInfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String captcha = redisCache.getCacheMapValue(CacheConstants.CAPTCHA_CODE_KEY,uuid);
        redisCache.delCacheMapValue(CacheConstants.CAPTCHA_CODE_KEY,uuid);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }

}
